package com.dmcb.common.business.utils;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;

/**
 * Jedis IP 工具类
 * Created by long on 2016/10/11.
 */
public class JedisHelper {

    public static final String PROXY_IP = "proxy.ip.";
    private static final ShardedJedisPool shardedJedisPool;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setTestOnBorrow(true);
        final JedisShardInfo info = new JedisShardInfo("103.205.5.5", 6379);
        info.setPassword("Kbq123456789Kbq");
        shardedJedisPool = new ShardedJedisPool(config, new ArrayList<JedisShardInfo>() {{
            add(info);
        }});
    }

    /**
     * 获取IP
     *
     * @param region 区域
     * @return IP
     */
    public static String getIp(String region) {
        return get(PROXY_IP + region, "");
    }

    /**
     * 设置IP
     *
     * @param region 区域
     * @param ip     IP
     * @return status
     */
    public static boolean setIp(String region, String ip) {
        return set(PROXY_IP + region, ip);
    }

    public static String get(String key, String defaultValue) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = shardedJedisPool.getResource();
            return shardedJedis.get(key) == null ? defaultValue : shardedJedis.get(key);
        } catch (Exception ex) {
            System.err.println("get error." + ex.getMessage());
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return defaultValue;
    }

    public static boolean set(String key, String value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.set(key, value);
            return true;
        } catch (Exception ex) {
            System.err.println("set error." + ex.getMessage());
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    private static void returnBrokenResource(ShardedJedis shardedJedis) {
        try {
            shardedJedisPool.returnBrokenResource(shardedJedis);
        } catch (Exception e) {
            System.err.println("returnBrokenResource error.");
        }
    }

    private static void returnResource(ShardedJedis shardedJedis) {
        try {
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            System.err.println("returnResource error.");
        }
    }

    public static void changeIp(){
        try {
            JedisHelper.setIp(WebClientUtil.PROXY_REGION, "");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
